/*Author: Rony Lahav (ID:043489889)*/

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;


/**
 * This class handles a single TCP incoming session - opens a connection, sends a GET message and receives the relevant file
 */
public class SingleTCPOutgoingConnection implements Runnable{

	Socket s = null;
	String fileName=null;
	int fileSize=0;
	boolean success=false;
	long uniqueID;
	PrintStream ps = null;
	BufferedReader br = null;
	
	public SingleTCPOutgoingConnection(String IP, int TCPPort, String fileName, int fileSize, long uniqueID) {
		this.uniqueID = uniqueID;
		try {
			this.s=new Socket(IP,TCPPort);	//open a TCP connection to sending peer
			success=true;
			this.fileName=fileName;
			this.fileSize=fileSize;
		} catch (UnknownHostException e) {}
		catch (IOException e) {}
	}
	
	public void run(){
		try{
			if (success)	//connection was established
				TCPHandleConnection();
		}
		catch(Exception e){
		}
		finally{
			try {
				if (br!=null)
					br.close();
				if (ps!=null)
					ps.close();
			} catch (IOException e) {}
			final_project.removeThreadFromLivingList(uniqueID);
		}
	}
	
	/**
	 * sends a GET message and receives the relevant file
	 */
	public void TCPHandleConnection() {
		try {
			if (!final_project.isShutDown()){
				br = new BufferedReader(new InputStreamReader(s.getInputStream()));
				ps = new PrintStream(s.getOutputStream());
				//send get
				String GETmsg = MessageCenter.getInstance().createMessage_GET(fileName);
				ps.print(GETmsg);
				//Receive file and store it
				int[] fileBuffer = readFile();
				FileOutputStream out = new FileOutputStream(new File(final_project.currentDir+"/files/"+fileName));
				byte[] pic = new byte[fileBuffer.length];
				for (int i = 0; i < pic.length;pic[i]=(byte) fileBuffer[i], i++);
				out.write(pic);
				out.flush();
				out.close();
			}
		}
		catch (SocketTimeoutException e1){}
		catch (IOException e2){}
	}

	public long getUniqueID(){
		return uniqueID;
	}
	
	/*read file from input stream*/
	private int[] readFile() throws IOException{
		int[] fileBuffer = new int[fileSize];
		int location=0;
		int intRead;
		do{
			 intRead = br.read();
			 fileBuffer[location]=intRead;
			 ++location;
		}while(location!=fileSize && !final_project.isShutDown());
		
		return fileBuffer;
	}
}
